import UIKit
import BUAdSDK


class BaseTabBarController: UITabBarController {
    
    var customTab: BaseTabBar!
    
    private var splashAd: BUSplashAd?
    private var isLoadAd = false
    
    // 处理广告10s未关闭直接关闭占位
    private var countdown = 10
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        DispatchQueue.main.async {
            
            AppThemeManager.keyWindow()?.addSubview(self.previewView)
            
            var list = [TabBarItemModel]()

            for item in self.tabBar.items! {
                list.append(TabBarItemModel(t: item.title ?? "", i: item.image ?? UIImage(), s: item.selectedImage ?? UIImage()))
            }

            self.customTab = BaseTabBar(frame: .zero, itemModel: list, currentSelect: self.selectedIndex)
            self.customTab.frame = self.tabBar.frame
            self.customTab.delegate = self
            self.customTab.tabBarDelegate = self
            self.setValue(self.customTab, forKey: "tabBar")
            
        }
        
        kUserManager.getUserInfomation { _ in }
        
        // 监听网络
        NetWorkManager.shared.startMonitoring()
        // 网络切换通知
        NotificationCenter.default.addObserver(self, selector: #selector(networkStatusSwitchNotification), name: kNetworkStatusNotification, object: nil)
        // 手动选中tabbar
        NotificationCenter.default.addObserver(self, selector: #selector(selectTabbarNotification(_:)), name: NSNotification.Name("SelectTabbarIndexNotification"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(reloadItem), name: NSNotification.Name("TabbarReloadItemNotification"), object: nil)
        // 广告初始化成功
        NotificationCenter.default.addObserver(self, selector: #selector(getAdData), name: NSNotification.Name("AdsInitSuccessNotification"), object: nil)

    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        // 去除tabbar 黑线
        tabBar.backgroundImage = UIImage.init()
        tabBar.shadowImage = UIImage.init()
        
        //NotificationCenter.default.addObserver(self, selector: #selector(getAppVerisonInfomation), name: UIApplication.willEnterForegroundNotification, object: nil)
    }
    @objc func reloadItem() {
        
        guard customTab.itemModels.count > 0 else { return }
        for index in 0 ..< customTab.itemModels.count {
            
            if let subItem = view.viewWithTag(8880+index) as? TabBar_Item, index < customTab.itemModels.count {
                print(customTab.itemModels[index].title)
                subItem.configData(model: customTab.itemModels[index])
            }
            
        }
        
    }
    private lazy var previewView = AppPreviewView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight))

    deinit {
        NetWorkManager.shared.stopMonitoring()
        NotificationCenter.default.removeObserver(self)
    }
    
    // MARK: - 全局通知处理
    @objc func networkStatusSwitchNotification() {
        switch NetWorkManager.shared.networkStatus {
        case .cellular, .ethernetOrWiFi:
            if AppGlobalConfigManager.config.isInitThridSdk == false {
                NotificationCenter.default.post(name: NSNotification.Name("ThirdAuthChooseNotification"), object: nil)
            }
            NotificationCenter.default.post(name: NSNotification.Name("ReloadHomeDataNotification"), object: nil)
        default:
            closePreview()
            break;
        }
    }
    @objc func selectTabbarNotification(_ notification: Notification) {
        guard let userInfo = notification.userInfo, let index = userInfo["index"] as? Int, index != -1 else { return }
//        customTab.switchItem(index: index)
    }

}

// MARK: - TabBarDelegate
extension BaseTabBarController: TabBarDelegate {
    
    func shouldSelect(index: Int) -> Bool {
        
        if index == 3 {
            guard let currentVC = Utils.getTopVC(), kUserManager.isLogin == false else { return true }
            currentVC.showDetailViewController(BaseNavigationController(rootViewController: LoginVC(viewType: .account)), sender: nil)
            return false
        } else {
            // 更新分类
            // AppGlobalConfigManager.config.getGlobalDictionary()
        }
        
        return true
    }
    

    @objc func singleTap(tabBar: BaseTabBar, index: Int)  {
        selectedIndex = index
        
    }
    
    func unselectItem(tabBar: BaseTabBar, index: Int) {
        
    }

}

// MARK: - 屏幕旋转
extension BaseTabBarController {
    
    override var shouldAutorotate: Bool {
        return self.selectedViewController?.shouldAutorotate ?? true
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return self.selectedViewController?.supportedInterfaceOrientations ?? .portrait
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return self.selectedViewController?.preferredInterfaceOrientationForPresentation ?? .portrait
    }
    
}

// MARK: - 加载开屏广告
extension BaseTabBarController: BUSplashAdDelegate {
    
    func startDetectionAd() {
        AppGCDTimer.shared.scheduledDispatchTimer(WithTimerName: "DetectionOpenAd", timeInterval: 1.0, queue: .main, repeats: true) { [weak self] in
            guard let strongSelf = self else { return }
            if strongSelf.countdown <= 0 {
                strongSelf.stopDetectionAd()
            } else {
                strongSelf.countdown -= 1
            }
        }
    }
    func stopDetectionAd() {
        AppGCDTimer.shared.cancelTimer(WithTimerName: "DetectionOpenAd")
        closePreview()
    }
    
    // 加载广告信息
    @objc private func getAdData() {
        splashAd = kAdsManager.loadOpeningTheAdvertising(delegate: self)
        if splashAd != nil {
            splashAd?.loadData()
        } else {
            kAdsManager.requestAdsIdList { [weak self] dialog in
                guard let strongSelf = self else { return }
                DispatchQueue.main.async {
                    if dialog.code == 200 && dialog.data != nil {
                        strongSelf.splashAd = kAdsManager.loadOpeningTheAdvertising(delegate: strongSelf)
                        strongSelf.splashAd?.loadData()
                    } else {
                        strongSelf.closePreview()
                    }
                }
            }
        }
        
    }
    // 关闭广告
    private func closePreview(isFinish: Bool = true) {
        previewView.isHidden = true
        
        guard isLoadAd == false, isFinish == true else { return }
        isLoadAd = true
        NotificationCenter.default.post(name: NSNotification.Name("HomeCheckUpgradeNotification"), object: nil)
    }
    
    //  - BUSplashAdDelegate
    func splashAdLoadSuccess(_ splashAd: BUSplashAd) {
        splashAd.showSplashView(inRootViewController: self)
        startDetectionAd()
    }
    
    func splashAdLoadFail(_ splashAd: BUSplashAd, error: BUAdError?) {
        closePreview()
    }
    
    func splashAdRenderSuccess(_ splashAd: BUSplashAd) {}
    
    func splashAdRenderFail(_ splashAd: BUSplashAd, error: BUAdError?) {
        closePreview()
    }
    
    func splashAdWillShow(_ splashAd: BUSplashAd) { 
        closePreview(isFinish: false)
    }
    
    func splashAdDidShow(_ splashAd: BUSplashAd) {}
    func splashAdDidClick(_ splashAd: BUSplashAd) {}
    
    func splashAdDidClose(_ splashAd: BUSplashAd, closeType: BUSplashAdCloseType) {
        closePreview()
    }
    
    func splashAdViewControllerDidClose(_ splashAd: BUSplashAd) {}
    func splashDidCloseOtherController(_ splashAd: BUSplashAd, interactionType: BUInteractionType) {}
    
    func splashVideoAdDidPlayFinish(_ splashAd: BUSplashAd, didFailWithError error: Error?) {
        closePreview()
    }
    
}




